<?php

class VideosController extends AppController {
	var $uses = array('Video','Author','Course');

    function backend_index(){
        $this->set('videos',$this->Video->find('all'));
    }
    
    function backend_new(){
        $this->__formProccessing();
    }
    
    function backend_edit($id=null){
        $this->__formProccessing($id);
    }
    
    function backend_delete($id){
        if($this->Video->delete($id))
            $this->Session->setFlash('El registro fue eliminado con exito.','ok');
        else
            $this->Session->setFlash('Hubo un error al eliminar el registro.','error');
        $this->redirect(array('action'=>'index'));
    }
    
    private function __formProccessing($id=null){
        if(!empty($this->request->data)){
            if(!$id)
                $this->Video->create();
            if($this->Video->save($this->request->data)){
            	$this->__calcCoursePrice($this->request->data['Video']['course_id']);
                $this->Session->setFlash('El registro fue guardado con exito.','ok');
                $this->redirect(array('action'=>'index'));
            }else{
                $this->Session->setFlash('Hubo un error al procesar el registro.','error');
            }
        }
        if(is_numeric($id))
            $this->request->data = $this->Video->findById($id);
        $this->set('authors',$this->Author->find('list'));
        $options['fields'] = array('id','title');
        $this->set('courses',$this->Course->find('list',$options));

    }
    
    private function __calcCoursePrice($course_id){
    	$course = $this->Course->findById($course_id);
		$coursePrice = 0;
    	foreach ($course['Video'] as $video){
    		$coursePrice = $coursePrice + $video['price'];
    	}
    	$course['Course']['price'] = $coursePrice * $course['Course']['percentage'];
    	$this->Course->save($course['Course']);
    }
}

?>
